package com.jiugang.cardump.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


@Component
public class CorsInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

		String[] allowDomain = {"http://120.55.40.9:7000","http://125.55.40.9:7002"};
		Set<String> allowedOrigins = new HashSet<String>(Arrays.asList(allowDomain));
		String originHeader = request.getHeader("Origin");
		if(allowedOrigins.contains(originHeader)){
			response.setHeader("Access-Control-Allow-Origin",originHeader);
		}

		//跨域请求，*代表允许全部类型
		//response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
		//允许请求方式
		response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
		//用来指定本次预检请求的有效期，单位为秒，在此期间不用发出另一条预检请求
		response.setHeader("Access-Control-Max-Age", "3600");
		//请求包含的字段内容，如有多个可用哪个逗号分隔如下
		response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,Authorization, x-ui-request,lang");
		//访问控制允许凭据，true为允许
		response.setHeader("Access-Control-Allow-Credentials", "true");
		// 如果是OPTIONS则结束请求
		if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
			response.setStatus(HttpStatus.NO_CONTENT.value());
			return false;
		}
		return true;
	}

}

